package cn.project.engineering.ui

import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import android.text.format.DateUtils
import android.util.Log
import android.view.KeyEvent
import android.view.View
import androidx.annotation.RequiresApi
import cn.project.engineering.R
import cn.project.engineering.base.MyAppCompatActivity
import cn.project.engineering.constant.GwConstant
import cn.project.engineering.http.HttpClient
import cn.project.engineering.http.RequestCallback
import cn.project.engineering.http.bean.ApkInfo
import cn.project.engineering.http.bean.FactoryInfo
import cn.project.engineering.http.bean.RequestError
import cn.project.engineering.http.bean.YvminInfo
import cn.project.engineering.service.LoopJobService
import cn.project.engineering.ui.view.WonderfulDialog
import cn.project.engineering.utils.*
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.XXPermissions
import kotlinx.android.synthetic.main.activity_splash.*
import log.KLog
import me.jessyan.retrofiturlmanager.RetrofitUrlManager
import java.io.File
import kotlin.system.exitProcess

/**
 *
 * @author  lifuhai
 * @date 2021/2/19 8:29
 */
class SplashActivity : MyAppCompatActivity() {

    companion object {
        private const val TAG = "SplashActivity"
        private const val STRPASSWORD = "123"


        /**
         * 倒计时 10s
         */
        private const val DATA_REFRESH_TIME = 1 * DateUtils.SECOND_IN_MILLIS
    }

    private var totleTime: Int = 30;
    private var factoryInfo: FactoryInfo? = null
    private var loadDataFinish = false
    var isPeizi=false
    private  var  blackMa:Int=0;

    private val handler = Handler(Looper.getMainLooper())

    /**
     * 数据刷新线程
     */
    private val refreshDataRunnable = object : Runnable {
        override fun run() {
            totleTime--;
            if (loading){
                time.setText("正在下载中。。。" )
            }else{
                time.setText("" + totleTime + "s")
            }
            if (totleTime == 0) {
                handler.removeCallbacks(this)
                if (!loadDataFinish) {
                    toast(R.string.gw_wait_for_data_loading)
                    return
                }
                if (!loading){
                    MainActivity.start(this@SplashActivity, factoryInfo)
                    time.visibility = View.GONE
                }
                return
            }
            handler.postDelayed(this, DATA_REFRESH_TIME);

        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_splash)
        val dataNomal = WonderSp.getDataNomal(this, "yuming");
        if(!TextUtils.isEmpty(dataNomal)){
            HttpClient.changeUrl(dataNomal);
            yumian.setText(dataNomal+"")
            putongjiemina()

        }else{
            ympeizi.visibility=View.VISIBLE
            infon.visibility=View.GONE
        }
        XXPermissions.with(this).permission(permission_array)
                .request(object : OnPermissionCallback {
                    override fun onGranted(permissions: List<String>, all: Boolean) {
                        if (all) {
//                            MainActivity.start(this@SplashActivity, factoryInfo)
//                            handler.removeCallbacks(refreshDataRunnable)

                        }
                    }

                    override fun onDenied(permissions: List<String>, never: Boolean) {
                        for (i in permissions.indices) {
                            val permission = permissions[i]
                            toast("${permission}权限未允许，请重新选择")
                        }
                    }
                })

        banben.setOnClickListener(View.OnClickListener {
            blackMa++;
            if (blackMa==5){
                ympeizi.visibility=View.VISIBLE
                handler.removeCallbacks(refreshDataRunnable)
                blackMa=0
            }

        })
        peizhi.setOnClickListener(View.OnClickListener {
            try {
                AppUtils.hideInput(this)
                if(AppUtils.isURL2(yumian.text.toString().trim())){
                    HttpClient.changeUrl(yumian.text.toString().trim());
                    HttpClient.httpService().checkYvmian().enqueue(object : RequestCallback<List<YvminInfo>> {
                        override fun onRequestSuccess(body: List<YvminInfo>?) {
                            body?.let {
                                if (it[0].Column1==1){
                                    WonderSp.putDataNomal(this@SplashActivity,"yuming",yumian.text.toString().trim())
                                    RetrofitUrlManager.getInstance().setGlobalDomain(yumian.text.toString().trim());
                                    putongjiemina()
                                }
                            }

                        }
                        override fun onRequestFail(error: RequestError) {

                            toast("域名不可用")
                        }

                    })
                }else{
                    toast("请输入正确的域名")
                }

            }catch (e :Exception){
                toast("请输入正确的域名")
            }



        })


        // tc
        btnExit.setOnClickListener {
            WonderfulDialog.passDialog(this,object :DialogCallback{
                @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
                override fun confirm(value: String?) {
                    toast(value+"---")
                    if (value != null) {
                        if (value.equals(STRPASSWORD)) {
                            var ostype = WonderSp.getDataNomal(this@SplashActivity, "ostype");
                            when (ostype) {
                                "V001" -> {
                                    //没获取到voo1 ？

                                    finish()
                                    jumpLauncher3()
                                    showBar()
                                    LoopJobService.stopDaemon(this@SplashActivity)
                                    android.os.Process.killProcess(android.os.Process.myPid())    //获取PID
                                    System.exit(0);   //常规java、c#的标准退出法，返回值为0代表正常退出
                                }
                                "V002" -> {

                                    finish()
                                    LoopJobService.stopDaemon(this@SplashActivity)
                                    android.os.Process.killProcess(android.os.Process.myPid())    //获取PID
                                    System.exit(0);   //常规java、c#的标准退出法，返回值为0代表正常退出
                                }

                                "" -> {
                                    finish()
                                    jumpLauncher3()
                                    showBar()
                                    LoopJobService.stopDaemon(this@SplashActivity)
                                    android.os.Process.killProcess(android.os.Process.myPid())    //获取PID
                                    System.exit(0);   //常规java、c#的标准退出法，返回值为0代表正常退出


                                }

                            }
                        }
//                        getPass(value)
                    }
                }

                override fun cancel() {
                }
            },"")

        }


    }

    override fun netWork(isnet: Boolean) {

        if (isnet){
            val dataNomal = WonderSp.getDataNomal(this, "yuming");
            if(!TextUtils.isEmpty(dataNomal)){
                handler.removeCallbacks(refreshDataRunnable)
                handler.postDelayed(refreshDataRunnable,DATA_REFRESH_TIME)
                initData()
            }

        }else{
            toast("网络连接失败，请检查网络设置")
            handler.removeCallbacks(refreshDataRunnable)
        }


    }

    private fun initView() {

        banben.setText("版本名："+AppUtils.getVersionName(this)+"版本号："+AppUtils.getVersionCode(this))
        btnMain.setOnClickListener {
            if (!loadDataFinish) {
                toast(R.string.gw_wait_for_data_loading)
                return@setOnClickListener
            }
            if (factoryInfo==null){
                return@setOnClickListener
            }
            handler.removeCallbacksAndMessages(null);
            MainActivity.start(this@SplashActivity, factoryInfo)


        }

        btnClear.setOnClickListener {
            DataCleanManager.clearAllCache(this)
            toast(R.string.gw_clear_data_completed)
        }


    }
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        when (keyCode) {
            KeyEvent.KEYCODE_BACK -> {
                //showBar()
                //jumpLauncher3()
                return true
            }
            KeyEvent.KEYCODE_HOME -> {
                return true
            }
        }
        return super.onKeyDown(keyCode, event)
    }

    private fun initData() {
        textIp.text = String.format(getString(R.string.gw_ip_X), IpAddressUtils.getIpAddress())
        textMAC.text = String.format(getString(R.string.gw_mac_X), IpAddressUtils.getMacAddress())

        HttpClient.httpService().getFactoryInfo(MacIP = IpAddressUtils.getMacAddress()).enqueue(object : RequestCallback<List<FactoryInfo>> {
            override fun onRequestSuccess(body: List<FactoryInfo>?) {
                loadDataFinish = true
                body?.let {
                    if (it.isNotEmpty()) {
                        factoryInfo = it[0]
                        textCompanyName.text = String.format(getString(R.string.gw_factory_X), factoryInfo?.FactoryName)
                        textStr1.text = String.format(getString(R.string.gw_workshop_X), factoryInfo?.WorkName)
                        textStr2.text = String.format(getString(R.string.gw_line_type_X), factoryInfo?.LineName)
                        textWork.text = String.format(getString(R.string.gw_station_X), factoryInfo?.MachineName)
                        WonderSp.putDataNomal(this@SplashActivity,"ostype",factoryInfo?.VerType)
                    } else {
                        KLog.d(TAG, "获取工厂信息不存在")
                        toast("当前设备对应信息不存在")
                    }
                }
            }

            override fun onRequestFail(error: RequestError) {
                loadDataFinish = true
                KLog.d(TAG, "获取工厂信息出错，code:${error.code}，message:${error.message}")
                toast("当前设备对应信息获取出错：${error.message}")
            }
        })
    }








    override fun onDestroy() {
        super.onDestroy()
        // 清除定时任务
        AlarmManagerUtil.cancelAlarm(this, AlarmManagerUtil.SCREEN_CONTROL_ACTION,  GwConstant.OPEN_SCREEN_ALARM_ID)
        AlarmManagerUtil.cancelAlarm(this, AlarmManagerUtil.SCREEN_CONTROL_ACTION,  GwConstant.CLOSE_SCREEN_ALARM_ID)
        exitProcess(0)
    }

    fun  putongjiemina(){
        ympeizi.visibility=View.GONE
        infon.visibility=View.VISIBLE
        //检查升级
//        myCheckApkInfor()
        // 清除之前的定时任务
        AlarmManagerUtil.cancelAlarm(this, AlarmManagerUtil.SCREEN_CONTROL_ACTION, GwConstant.OPEN_SCREEN_ALARM_ID)
        AlarmManagerUtil.cancelAlarm(this, AlarmManagerUtil.SCREEN_CONTROL_ACTION, GwConstant.CLOSE_SCREEN_ALARM_ID)
        initView()
        initData()
//        checkScreenControl()

        // 10s后进入首页

        time.setText("" + totleTime + "s")
        if (AppUtils.isNetworkAvailable(this)){
            handler.postDelayed(refreshDataRunnable, DATA_REFRESH_TIME)
        }

    }


    //检查更新
    fun myCheckApkInfor() {
        XXPermissions.with(this).permission(permission_array)
                .request(object : OnPermissionCallback {
                    override fun onGranted(permissions: List<String>, all: Boolean) {
                        if (all) {
                            HttpClient.httpService().checkApk().enqueue(object : RequestCallback<List<ApkInfo>> {
                                override fun onRequestSuccess(body: List<ApkInfo>?) {
                                    body?.let {
                                        if (it.isNotEmpty()) {
                                            val apkInfo = it[0]
                                            if (apkInfo.UnitName.toInt()>AppUtils.getVersionCode(this@SplashActivity)){
                                                handler.removeCallbacks(refreshDataRunnable)
                                                Thread(object : Runnable{
                                                    override fun run() {
                                                        DownloadUtil.get().download(apkInfo.APK,PathUtil.BASE_FILE_URL,"gwesop.apk",object :DownloadUtil.OnDownloadListener{
                                                            override fun onDownloadSuccess(file: File?) {
                                                                handler.postDelayed(refreshDataRunnable, DATA_REFRESH_TIME);
                                                                runOnUiThread(object :Runnable{
                                                                    override fun run() {
                                                                        toast("下载完成")
                                                                    }
                                                                })
                                                                KLog.debug(TAG,"onDownloadSuccess")
//                                                                AppUtils.installApk(this@MyAppCompatActivity)
                                                                var  ostype=WonderSp.getDataNomal(this@SplashActivity,"ostype");
                                                                when (ostype) {
                                                                    "V001" -> {
                                                                        val intent = Intent()
                                                                        intent.action = "com.slx.InstallSlient"
                                                                        intent.putExtra("path", PathUtil.BASE_FILE_URL + "/gwesop.apk")
                                                                        this@SplashActivity.sendBroadcast(intent)
                                                                    }
                                                                    "V002" -> {
//                                                                        runOnUiThread(object :Runnable{
//                                                                            override fun run() {
//                                                                                toast(PathUtil.BASE_FILE_URL + "/gwesop.apk")                                                                    }
//                                                                        })
                                                                        val intent = Intent()
                                                                        intent.action="cms.intent.action.UPDATE_APK"
                                                                        intent.putExtra("filePath", PathUtil.BASE_FILE_URL + "/gwesop.apk")
                                                                        intent.putExtra("keep",true)
                                                                        intent.putExtra("packageName", "cn.project.engineering")
                                                                        intent.putExtra("activityName", "cn.project.engineering.ui.SplashActivity")
                                                                        this@SplashActivity.sendBroadcast(intent)

                                                                    }
                                                                }
                                                                loading=false;
                                                            }
                                                            override fun onDownloadFailed(e: Exception?) {
                                                                runOnUiThread(object :Runnable{
                                                                    override fun run() {
                                                                        toast("下载失败")
                                                                        time.setText("下载失败" )

                                                                    }
                                                                })

                                                                KLog.debug(TAG,"onDownloadFailed"+e.toString())
                                                                loading=false;
                                                            }

                                                            override fun onDownloading(progress: Int) {

                                                                runOnUiThread(object :Runnable{
                                                                    override fun run() {
                                                                        time.setText("正在下载中。。。" )
//                                                                        toast("正在下载进度" + progress)
                                                                    }
                                                                })

                                                                loading=true

                                                                KLog.debug(TAG,"onDownloading"+Int)
                                                            }

                                                        })
                                                    }
                                                }).start()

                                            }

                                        }else{

                                        }
                                    }

                                }

                                override fun onRequestFail(error: RequestError) {

                                }

                            })

                        }
                    }

                    override fun onDenied(permissions: List<String>, never: Boolean) {
                        for (i in permissions.indices) {
                            val permission = permissions[i]
                            toast("${permission}权限未允许，请重新选择")
                        }
                    }
                })

    }

}


